﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//引用的命名空间
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Web;

namespace DotNet.WebUI
{
    /// <summary>
    /// 验证码
    /// </summary>
    public class ProvingCode
    {
        public ProvingCode()
        {

        }

        #region 数字验证码

        /// <summary>
        /// 纯数字验证码
        /// </summary>
        /// <param name="codeCount">验证码个数</param>
        /// <returns></returns>
        public string GetRandomint(int codeCount)
        {
            Random rand = new Random();
            string min = "";
            string max = "";
            for (int i = 0; i < codeCount; i++)
            {
                min += "1";
                max += "9";
            }
            return (rand.Next(Convert.ToInt32(min), Convert.ToInt32(max)).ToString());
        }

        /// <summary>
        /// 纯数字验证码
        /// </summary>
        /// <param name="codeCount">验证码个数</param>
        /// <returns></returns>
        public string CreateRandomCode(int codeCount)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9";
            string[] allCharArray = allChar.Split(',');
            string randomCode = "";
            int temp = -1;//记录上次随机数值，尽量避避免生产几个一样的随机数
            Random rand = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }

                int t = rand.Next(9);
                if (temp == t)
                {
                    return CreateRandomCode(codeCount);
                }

                temp = t;
                randomCode += allCharArray[t];
            }
            return randomCode;
        }

        #endregion

        #region 数字+字母验证码

        /// <summary>
        /// 数字与字母的验证码
        /// </summary>
        /// <param name="codeCount">验证码个数</param>
        /// <returns></returns>
        public string CreateStringCode(int codeCount)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
            string[] allCharArray = allChar.Split(',');
            string randomCode = "";
            int temp = -1;
            Random rand = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }

                int t = rand.Next(61);
                if (temp == t)
                {
                    return CreateStringCode(codeCount);

                }

                temp = t;
                randomCode += allCharArray[t];
            }

            return randomCode;
        }

        #endregion

        #region 中文汉字验证码

        /// <summary>
        /// 中文汉字验证码，此函数在汉字编码范围内随机创建含两个元素的十六进制字节数组，每个字节数组代表一个汉字，并将四个字节数组存储在object数组中
        /// </summary>
        /// <param name="strlength">验证码个数</param>
        /// <returns></returns>
        private object[] CreateRegionCode(int strlength)
        {
            //定义一个字符串数组储存汉字编码的组成元素 
            string[] rBase = new String[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
            Random rnd = new Random();
            //定义一个object数组用来 
            object[] bytes = new object[strlength];

            /*每循环一次产生一个含两个元素的十六进制字节数组，并将其放入bject数组中
            每个汉字有四个区位码组成 
            区位码第1位和区位码第2位作为字节数组第一个元素 
            区位码第3位和区位码第4位作为字节数组第二个元素 
        */

            for (int i = 0; i < strlength; i++)
            {
                //区位码第1位 
                int r1 = rnd.Next(11, 14);
                string str_r1 = rBase[r1].Trim();

                //区位码第2位 
                rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i);//更换随机数发生器的种子避免产生重复值
                int r2;
                if (r1 == 13)
                {
                    r2 = rnd.Next(0, 7);
                }
                else
                {
                    r2 = rnd.Next(0, 16);
                }

                string str_r2 = rBase[r2].Trim();

                //区位码第3位 
                rnd = new Random(r2 * unchecked((int)DateTime.Now.Ticks) + i);
                int r3 = rnd.Next(10, 16);
                string str_r3 = rBase[r3].Trim();

                //区位码第4位 
                rnd = new Random(r3 * unchecked((int)DateTime.Now.Ticks) + i);
                int r4;
                if (r3 == 10)
                {
                    r4 = rnd.Next(1, 16);
                }
                else if (r3 == 15)
                {
                    r4 = rnd.Next(0, 15);
                }
                else
                {
                    r4 = rnd.Next(0, 16);
                }
                string str_r4 = rBase[r4].Trim();

                //定义两个字节变量存储产生的随机汉字区位码 
                byte byte1 = Convert.ToByte(str_r1 + str_r2, 16);
                byte byte2 = Convert.ToByte(str_r3 + str_r4, 16);

                //将两个字节变量存储在字节数组中 
                byte[] str_r = new byte[] { byte1, byte2 };

                //将产生的一个汉字的字节数组放入object数组中 
                bytes.SetValue(str_r, i);
            }

            return bytes;
        }

        /// <summary>
        /// 生成4个中文随机汉字
        /// </summary>
        /// <returns></returns>
        public string CreateCNCode()
        {
            System.Text.Encoding gb = System.Text.Encoding.GetEncoding("gb2312");

            object[] bytes = CreateRegionCode(4);

            string str1 = gb.GetString((byte[])Convert.ChangeType(bytes[0], typeof(byte[])));

            string str2 = gb.GetString((byte[])Convert.ChangeType(bytes[1], typeof(byte[])));

            string str3 = gb.GetString((byte[])Convert.ChangeType(bytes[2], typeof(byte[])));

            string str4 = gb.GetString((byte[])Convert.ChangeType(bytes[3], typeof(byte[])));

            string checkCode = str1 + str2 + str3 + str4;

            return checkCode;
        }

        #endregion

        #region 生成图片

        /// <summary>
        /// 生成图片
        /// </summary>
        /// <param name="validata">验证码</param>
        public void CreateImage(string validata)
        {
            //若校验码为空,则直接返回
            if (string.IsNullOrEmpty(validata))
            {
                return;
            }

            //验证码存储在Session中，供验证
            System.Web.HttpContext.Current.Session.Add("ValidateCode", validata);
            Bitmap img = null;
            Graphics g = null;
            MemoryStream ms = null;
            Random rand = new Random();

            //验证码颜色集合
            Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };

            //验证码字体集合 
            String[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };

            //定义图像的大小，生成图像的实例
            img = new Bitmap((int)Math.Ceiling(Convert.ToDecimal(validata.Length * 18)), 28);

            //从Img对象生成新的Graphics对象
            g = Graphics.FromImage(img);

            //背景设为白色
            g.Clear(Color.White);

            //在随机位置画背景点
            for (int i = 0; i < 100; i++)
            {
                int x = rand.Next(img.Width);
                int y = rand.Next(img.Height);
                g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
            }

            //验证码绘制在g中
            for (int i = 0; i < validata.Length; i++)
            {
                int cindex = rand.Next(7);//随机颜色索引值
                int findex = rand.Next(5);//随机字体索引值
                Font f = new Font(fonts[findex], 13, FontStyle.Bold);//字体
                Brush b = new SolidBrush(c[cindex]);//颜色
                int ii = 4;

                if ((i + 1) % 2 == 0)//控制验证码不在同一高度
                {
                    ii = 2;
                }
                g.DrawString(validata.Substring(i, 1), f, b, 3 + (i * 16), ii);//绘制一个验证字符
            }

            ms = new MemoryStream();//生成内存流对象
            img.Save(ms, ImageFormat.Jpeg);//将此图像以Png图像文件的格式保存到流中

            //清除缓冲区流中的所有输出
            System.Web.HttpContext.Current.Response.ClearContent();

            //输出流的HHT MIME类型设置为"image/png"
            System.Web.HttpContext.Current.Response.ContentType = "image/Jpeg";

            //输出的图片的二进制流
            System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            System.Web.HttpContext.Current.Response.End();

            //回收资源 
            g.Dispose();
            img.Dispose();
            ms.Dispose();
        }


        /// <summary>
        /// 生成验证码图片
        /// </summary>
        /// <param name="checkCode">验证码</param>
        public void CreateCheckCodeImage(string checkCode)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return;
            int iWordWidth = 15;
            int iImageWidth = checkCode.Length * iWordWidth;
            Bitmap image = new Bitmap(iImageWidth, 20);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器 
                Random random = new Random();
                //清空图片背景色 
                g.Clear(Color.White);

                //画图片的背景噪音点
                for (int i = 0; i < 20; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }

                //画图片的背景噪音线 
                for (int i = 0; i < 2; i++)
                {
                    int x1 = 0;
                    int x2 = image.Width;
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    if (i == 0)
                    {
                        g.DrawLine(new Pen(Color.Gray, 2), x1, y1, x2, y2);
                    }

                }


                for (int i = 0; i < checkCode.Length; i++)
                {

                    string Code = checkCode[i].ToString();
                    int xLeft = iWordWidth * (i);
                    random = new Random(xLeft);
                    int iSeed = DateTime.Now.Millisecond;
                    int iValue = random.Next(iSeed) % 4;
                    if (iValue == 0)
                    {
                        Font font = new Font("Arial", 13, (FontStyle.Bold | System.Drawing.FontStyle.Italic));
                        Rectangle rc = new Rectangle(xLeft, 0, iWordWidth, image.Height);
                        LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Blue, Color.Red, 1.5f, true);
                        g.DrawString(Code, font, brush, xLeft, 2);
                    }
                    else if (iValue == 1)
                    {
                        Font font = new System.Drawing.Font("楷体", 13, (FontStyle.Bold));
                        Rectangle rc = new Rectangle(xLeft, 0, iWordWidth, image.Height);
                        LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Blue, Color.DarkRed, 1.3f, true);
                        g.DrawString(Code, font, brush, xLeft, 2);
                    }
                    else if (iValue == 2)
                    {
                        Font font = new System.Drawing.Font("宋体", 13, (System.Drawing.FontStyle.Bold));
                        Rectangle rc = new Rectangle(xLeft, 0, iWordWidth, image.Height);
                        LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Green, Color.Blue, 1.2f, true);
                        g.DrawString(Code, font, brush, xLeft, 2);
                    }
                    else if (iValue == 3)
                    {
                        Font font = new System.Drawing.Font("黑体", 13, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Bold));
                        Rectangle rc = new Rectangle(xLeft, 0, iWordWidth, image.Height);
                        LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Blue, Color.Green, 1.8f, true);
                        g.DrawString(Code, font, brush, xLeft, 2);
                    }
                }
                //////画图片的前景噪音点 
                //for (int i = 0; i < 8; i++)
                //{
                //    int x = random.Next(image.Width);
                //    int y = random.Next(image.Height);
                //    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                //}
                //画图片的边框线 
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                System.Web.HttpContext.Current.Response.ClearContent();
                System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }

        #endregion
    }
}